// #region [规格]
interface Attribute {
  key: string;
  value: string;
}

/**
 * 从DOMParser解析后的Document中提取产品属性信息
 * @param doc DOMParser解析HTML后得到的Document对象
 * @returns 提取到的属性数组
 */
const getAttributes = (doc: Document): Attribute[] => {
  const attributes: Attribute[] = [];

  // 处理tr.a-spacing-small元素
  const spacingRows = doc.querySelectorAll<HTMLTableRowElement>("tr.a-spacing-small");
  spacingRows.forEach((row) => {
    const attr: Attribute = { key: "", value: "" };
    const poClass = Array.from(row.classList).find(cls => cls.startsWith("po-"));
    attr.key = poClass ? poClass.replace("po-", "") : row.textContent?.trim() || "";
    const valueCell = row.querySelector<HTMLTableCellElement>("td.a-span9");
    attr.value = valueCell?.textContent?.trim() || "";
    
    if (attr.key.length > 0) {
      attributes.push(attr);
    }
  });

  // 处理品牌信息（#bylineInfo）
  const bylineInfo = doc.querySelector<HTMLAnchorElement>("a#bylineInfo")?.textContent;
  if (bylineInfo) {
    const storeMatch = bylineInfo.match(/Visit the (.+?) Store/);
    storeMatch?.[1] && attributes.push({ key: "Brand", value: storeMatch[1] });

    const colonMatch = bylineInfo.match(/^[^\s:\uff1a]+[:\uff1a]\s*(.+)$/);
    colonMatch?.[1] && attributes.push({ key: "Brand", value: colonMatch[1] });

    const jpStoreMatch = bylineInfo.match(/(.+?)\u306e\u30b9\u30c8\u30a2/);
    jpStoreMatch?.[1] && attributes.push({ key: "Brand", value: jpStoreMatch[1] });
  }

  // 处理table.prodDetTable表格
  const prodDetRows = doc.querySelectorAll<HTMLTableRowElement>("table.prodDetTable > tr");
  prodDetRows.forEach((row) => {
    const attr: Attribute = { key: "", value: "" };
    const keyCell = row.querySelector<HTMLTableCellElement>("th");
    const valueCell = row.querySelector<HTMLTableCellElement>("td");
    
    attr.key = keyCell?.textContent?.trim() || "";
    attr.value = valueCell?.textContent?.trim() || "";
    
    if (attr.key.length > 0) {
      attributes.push(attr);
    }
  });

  // 处理ul.detail-bullet-list列表
  const bulletItems = doc.querySelectorAll<HTMLSpanElement>(
    "ul.detail-bullet-list > li > span.a-list-item"
  );
  bulletItems.forEach((item) => {
    const attr: Attribute = { key: "", value: "" };
    const spans = item.querySelectorAll<HTMLSpanElement>("span");
    const keySpan = spans[0];
    const valueSpan = spans[1];

    // 处理key
    if (keySpan) {
      let keyText = keySpan.textContent || "";
      attr.key = keyText
        .replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2061-\u206F\uFEFF]/g, "")
        .replace(/\s+/g, " ")
        .replace(/^\s+|\s+$/g, "")
        .replace(":", "")
        .trim();
    }

    // 处理value
    if (valueSpan) {
      let valueText = valueSpan.textContent || "";
      attr.value = valueText
        .replace(/[\u0000-\u001F\u007F-\u009F\u200B-\u200F\u202A-\u202E\u2061-\u206F\uFEFF]/g, "")
        .replace(/\s+/g, " ")
        .replace(/^\s+|\s+$/g, "")
        .trim();
    }

    if (attr.key.length > 0) {
      attributes.push(attr);
    }
  });

  return attributes;
};

/**
 * 从商品详情页提取SKU的规格信息
 * @param doc 浏览器DOM Document对象
 * @returns SKU规格信息字典，未提取到时返回默认{"color_name": "default"}
 */
export function extractSkuSpecs(doc: Document): Record<string, string> {
  const specs: Record<string, string> = {};

  // 方法1: 从script标签的JSON数据提取规格（优先级最高）
  try {
    // 查找type="a-state"且含指定data-a-state的script标签
    const scriptTags = doc.querySelectorAll('script[type="a-state"]');
    scriptTags.forEach((script) => {
      const dataAState = script.getAttribute("data-a-state");
      if (
        dataAState &&
        dataAState.includes("desktop-twister-sort-filter-data")
      ) {
        try {
          // 解码JSON数据（对应Python的html.unescape）
          const unescapedState = decodeURIComponent(dataAState);
          const stateData = JSON.parse(unescapedState);

          if (stateData.key === "desktop-twister-sort-filter-data") {
            const scriptContent = script.textContent;
            if (scriptContent) {
              const jsonData = JSON.parse(scriptContent);
              const sortedDims = jsonData.sortedDimValuesForAllDims || {};

              // 遍历维度，提取选中状态的规格
              Object.entries(sortedDims).forEach(([dimName, dimValues]) => {
                if (Array.isArray(dimValues)) {
                  const selectedValue = dimValues.find(
                    (value) => value.dimensionValueState === "SELECTED"
                  );
                  if (selectedValue) {
                    specs[dimName] =
                      selectedValue.dimensionValueDisplayText || "";
                  }
                }
              });
            }
          }
        } catch (e) {
          console.debug(
            `从script标签提取规格信息失败: ${
              e instanceof Error ? e.message : String(e)
            }`
          );
        }
      }
    });
  } catch (e) {
    console.debug(
      `查找script标签时出错: ${e instanceof Error ? e.message : String(e)}`
    );
  }

  // 方法2: 处理 inline-twister-row-* 结构
  const inlineTwisterRows = doc.querySelectorAll(
    'div[id^="inline-twister-row-"]'
  );
  inlineTwisterRows.forEach((row) => {
    const rowId = row.id;
    if (rowId.startsWith("inline-twister-row-")) {
      const specType = rowId.slice("inline-twister-row-".length);
      const selectedValueElement = row.querySelector(
        'span[id^="inline-twister-expanded-dimension-text-"]'
      );

      if (selectedValueElement) {
        const specValue = selectedValueElement.textContent?.trim() || "";
        if (specValue) {
          specs[specType] = specValue;
        }
      }
    }
  });


  // 方法3: 处理 inline-twister-singleton-header-* 结构
  const singletonHeaders = doc.querySelectorAll(
    'div[id^="inline-twister-singleton-header-"]'
  );
  singletonHeaders.forEach((header) => {
    const headerId = header.id;
    if (headerId.startsWith("inline-twister-singleton-header-")) {
      const specType = headerId.slice(
        "inline-twister-singleton-header-".length
      );
      const selectedValueElement = header.querySelector(
        'span[id^="inline-twister-expanded-dimension-text-"]'
      );

      if (selectedValueElement) {
        const specValue = selectedValueElement.textContent?.trim() || "";
        if (specValue) {
          specs[specType] = specValue;
        }
      }
    }
  });

  // 方法4: 处理 variation_* 结构
  const variationDivs = doc.querySelectorAll('div[id^="variation_"]');
  variationDivs.forEach((div) => {
    const variationId = div.id;
    if (variationId.startsWith("variation_")) {
      const specType = variationId.slice("variation_".length);
      // 优先找dropdownSelect类的option，次找selected属性的option
      let selectedOption = div.querySelector("option.dropdownSelect");
      if (!selectedOption) {
        selectedOption = div.querySelector("option[selected]");
      }

      if (selectedOption) {
        const specValue = selectedOption.textContent?.trim() || "";
        specs[specType] = specValue;
      }
    }
  });

  // 方法5: 处理 native_dropdown_selected_* 结构
  const selectElements = doc.querySelectorAll(
    'select[id^="native_dropdown_selected_"]'
  );
  selectElements.forEach((select) => {
    const selectId = select.id;
    if (selectId.startsWith("native_dropdown_selected_")) {
      const specType = selectId.slice("native_dropdown_selected_".length);
      // 优先找selected属性的option，次找dropdownSelect类的option
      let selectedOption = select.querySelector("option[selected]");
      if (!selectedOption) {
        selectedOption = select.querySelector("option.dropdownSelect");
      }

      if (selectedOption) {
        const specValue = selectedOption.textContent?.trim() || "";
        specs[specType] = specValue;
      }
    }
  });

  // const attributes = getAttributes(doc);
  // attributes.forEach((attribute) =>{
  //   const { key, value } = attribute;
  //   if(['color'].includes(key)) {
  //     specs[key] = value;
  //   }
  // })

  // 所有方法均未提取到数据，返回默认值
  if (Object.keys(specs).length === 0) {
    console.info("未找到规格信息，返回默认值");
    return { color_name: "default" };
  }

  return specs;
}
// #endregion
